package com.rtsapp.server.gamelog.server.handler;

import com.rtsapp.server.common.IByteBuffer;
import com.rtsapp.server.gamelog.cmd.cmd.Commands;
import com.rtsapp.server.gamelog.server.service.ILogService;
import com.rtsapp.server.logger.Logger;
import com.rtsapp.server.logger.LoggerFactory;
import com.rtsapp.server.module.Application;
import com.rtsapp.server.network.protocol.command.AbstractCommandInHandler;
import com.rtsapp.server.network.protocol.command.ICommand;
import com.rtsapp.server.network.session.Session;
import com.rtsapp.server.network.session.SessionListener;
import com.rtsapp.server.network.session.SessionManager;
import com.rtsapp.server.network.session.netty.NettySessionManager;

public class CommandInHandler extends AbstractCommandInHandler {

	private static final Logger LOGGER = LoggerFactory.getLogger(CommandInHandler.class);

	private static final int LEN_FIELD_LEN = 4;
	private static final int COMMAND_ID_LEN  = 4;

	private ILogService service;


	public CommandInHandler(){

	}


	public boolean initialize( Application application, NettySessionManager sessionManager ){

		super.initialize(application, sessionManager);

		this.sessionManager.setSessionListener( new GamelogSessionListener() );

		return true;
	}

	public void setService(ILogService service) {
		this.service = service;
	}

	@Override
	public boolean processMessageHead(Session session, IByteBuffer buffer) {

		if( buffer.readableBytes() < ( LEN_FIELD_LEN  + COMMAND_ID_LEN) ){
			LOGGER.error("包长度错误 长度字段 < " + (LEN_FIELD_LEN + COMMAND_ID_LEN));
			LOGGER.error("数据包头部错误, 将关闭连接");
			session.close( );
			return false;
		}

		//读取包的长度, 这句代码不嗯给你删除
		int packLength = buffer.readInt();
		int commandId = buffer.getInt(buffer.readerIndex());


		//登陆,重登陆, 永远返回true, 如果后面已经有玩家在线,则会踢出在线的玩家，进行新的登录
		if(  commandId == Commands.Login ){
			return true;
		}


		return true;
	}


	/**
	 * 重写处理消息体的过程
	 * @param session
	 * @param buffer
	 */
	@Override
	public void processMessageBody( Session session,  IByteBuffer buffer ){


		//获得对应的handler
		int commandId = buffer.getInt(buffer.readerIndex());
		String commandIdStr  = Integer.toHexString(commandId).toUpperCase();

		//创建Request, Response
		ICommand request = Commands.createRequest(commandId);
		if( request == null  ){
			closeSession(session, null);
			return;
		}


		//读取request, 如果有异常报错
		try{
			request.readFromBuffer( buffer );
		}catch( Throwable ex) {
			closeSession( session, ex );
			return;
		}


		try {
			service.execute(session, commandId, request );
		}catch ( Throwable ex ){
			closeSession( session, ex );
		}
	}

	private void closeSession( Session session, Throwable ex ){
		if( ex != null ){
			LOGGER.error( ex);
		}

		session.close();
	}


	private class GamelogSessionListener implements SessionListener {

		@Override
		public void onSessionAdded(Session session, SessionManager sessionManager) {
			LOGGER.debug( "建立连接:{}", session.getRemoteAddress() );
		}

		@Override
		public void onSessionRemoved(Session session, SessionManager sessionManager) {

			LOGGER.debug("断开连接:{}", session.getRemoteAddress() );

		}

	}
}
